package com.whims.MemoryError.OutOfMemoryError;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * vm options:-Xmx20M -XX:MaxDirectMemorySize=10M
 * 本机直接内存溢出测试
 */
public class DirectMemoryOOM {

    private static final int _1MB = 1024 * 1024;

    public static void main(String [] args) throws IllegalAccessException {
        //通过反射获取Unsafe实例（jdk禁止实例）进行内存分配
        Field unsafeFile = Unsafe.class.getDeclaredFields()[0];
        unsafeFile.setAccessible(true);
        Unsafe unsafe = (Unsafe) unsafeFile.get(null);
        while (true) {
            //申请分配内存
            unsafe.allocateMemory(_1MB);
        }
    }


}
